package com.example.testone.utils

import android.util.Log
import com.example.testone.viewModels.SettingViewModel
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.util.SerialInputOutputManager
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
import java.io.IOException
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import javax.inject.Inject
import javax.inject.Singleton

interface SerialCallBackEvent{
    fun callbackData(bytes:ByteArray)
}

@Singleton
class SerialPortUtils @Inject constructor(val usbPermission: UsbPermission) {
    val TAG = "SerialPortUtil"

    var serialCallBackEvent:SerialCallBackEvent?=null

    var usbSerialPort: UsbSerialPort ?= null

    var settingViewModel:SettingViewModel?=null

    var usbIoManager: SerialInputOutputManager? = null
    private val mExecutor: ExecutorService = Executors.newSingleThreadExecutor()

    init {
        MyLog.print(TAG,"usbPermission.SerialPortUtil-----")
        connUsbSerialPort()
    }

    private fun connUsbSerialPort() {
        if(usbPermission.usbSerialPort==null){
            MyLog.print(TAG,"usbPermission.usbSerialPort=${usbPermission.usbSerialPort}")
            return
        }
        //打开usb连接
        usbSerialPort = usbPermission.usbSerialPort!!.let {
            try {
                it.open(usbPermission.connection)
                it.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

            }catch (e:IOException){
                e.printStackTrace()
            }
            it
        }
        if(usbSerialPort!=null){
            MyLog.print(TAG,  "SerialInputOutputManager--onCallbackEvent" )
            usbIoManager = SerialInputOutputManager(usbSerialPort, object : SerialInputOutputManager.Listener {
                override fun onNewData(data: ByteArray?) {
                    if (data != null) {
                        serialCallBackEvent?.callbackData(data)


                    }

                }

                override fun onRunError(e: Exception?) {
                    MyLog.print(TAG,  "SerialInputOutputManager--onRunError" + e.toString())
                }

            })
            mExecutor.submit(usbIoManager)
        }

    }

    fun sendMsg(buffer:ByteArray){

        if(usbSerialPort==null){
            MyLog.print(TAG,"sendMsg-usbPermission.usbSerialPort=${usbPermission.usbSerialPort}")
            return
        }
        MyLog.print(TAG, "usbSerialPort-isOpen.${usbSerialPort?.isOpen};buffer:${ByteUtil.toHexStr(buffer)}")
        if(!usbSerialPort!!.isOpen){
            connUsbSerialPort()
            return
        }
        try{
            usbSerialPort!!.write(buffer,1000)

        }catch (e:IOException){
            e.printStackTrace()
        }

    }


    fun test(){
        Log.e("-*--","SerialPortUtil.test,,${usbPermission.usbSerialPort}")
    }
}